let { table, $, form, layer } = layui;
export default class Cinema {
    constructor() {
        this.render();
        this.handle();
    }
    render() {
        let template = `
        <style>
        .size{
            width: 120px;
        }
        .width{
            width: 320px;
        }
        .seatTable{
            display: inline-block;  
            width: 30px;
            height: 30px;
            margin: 0 5px;
        }

        .red{
            background-color: red;

        }
        .black{

            background-color: dimgray;

        }
        .row{
            margin-left:110px;
        }
    </style>
    <table id="cinemaTable" lay-filter="cinemaTable"></table>
    <script type="text/html" id="tools">
        <form class="layui-form" lay-filter="searchForm">
            <div class="layui-input-inline">
                <button type="button" class="layui-btn layui-btn-primary layui-border-black" lay-event="add">  
                <i class="layui-icon">&#xe654;</i>
                <i class="layui-icon">新增院线</i>
                </button>
            </div>
           
    </div>
            <div class="layui-input-inline type size">
            <select name="type" >
            <option value="">全部</option>
                <option value="name">院线名</option>
                <option value="address">地址</option>
                <option value="phone">官方电话</option>
                <option value="email">官方网站</option>
            </select>
          </div>
          <div class="layui-input-inline value">
              <input type="text" name="value" placeholder="请输入搜索条件" class="layui-input">
          </div>
          <div class="layui-input-inline">
              <button type="button" lay-event="search" class="layui-btn layui-btn-primary layui-btn">
                  <i class="layui-icon">&#xe615;</i>
              </button>
          </div>
        </div>
        </form>
    </script>
    <script type="text/html" id="cinemaBar">
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="delete">删除</a>
    </script>
   `;
        $("#content").html(template);
    }
    handle() {
        table.render({
            elem: "#cinemaTable",
            url: "/cinema", //数据接口
            toolbar: "#tools",
            page: true, //开启分页
            request: {
                pageName: 'current' //页码的参数名称，默认：page
                , limitName: 'pageSize' //每页数据量的参数名，默认：limit
            },
            parseData: function (res) { //res 即为原始返回的数据
                return {
                    "code": 0, //解析接口状态
                    "count": res.total, //解析数据长度
                    "data": res.rows //解析数据列表
                };
            },
            limit: 3,
            limits: [3, 5, 10, 15, 20],
            cols: [
                [
                    //表头
                    {
                        field: "name",
                        title: "院线名",
                    },
                    {
                        field: "address",
                        title: "地址",
                    },
                    { field: "phone", title: "官方电话" },
                    { field: "email", title: "官方网站" },
                    { fixed: 'right', width: 150, align: 'center', toolbar: '#cinemaBar' }
                ],
            ],
        });
        //新增院线
        table.on('toolbar(cinemaTable)', function (obj) { //触发头部工具栏事件
            let keepIndex = 0; //设置初始化下标
            if (obj.event == "add") {
                layer.open({ //弹出层打开
                    type: 1,
                    title: '添加院线信息',
                    area: ['500px', '400px'],
                    btn: ['确定', '取消'],
                    yes: function (index) { //点击确定按钮函数
                        let screens = [];
                        for (let i = 0; i < keepIndex; i++) {
                            if ($("#addSeats" + i).length > 0) {
                                // console.log($("#addSeats" + i).length);
                                screens.push({
                                    name: $("#screensName" + i).val(),
                                    seat: JSON.parse($("#screensSeat" + i).val())
                                });
                            }
                        }

                        $.ajax({
                            type: "post",
                            url: "/cinema",
                            data: { ...form.val("addForm"), screens: JSON.stringify(screens) },
                            success() { //服务器响应成功
                                table.reload("cinemaTable"); //添加成功表格重载渲染
                                layer.close(index);
                            }
                        });

                    },
                    success: function () { //弹出层成功出现 
                        //新增放映厅
                        $("#addScreens").click(function () {
                            let str = `
                            <div id="addSeats${keepIndex}">
                            <div class="layui-form-item">
                            <label class="layui-form-label">放映厅:</label>
                            <div class="layui-input-inline">
                                <input
                                    type="text"
                                    id="screensName${keepIndex}"
                                    required
                                    lay-verify="required"
                                    placeholder="请输入放映厅" 
                                    autocomplete="off"
                                    class="layui-input div-width"
                                />
                            </div>
                        </div>
                        <div class="layui-form-item flex">
                            <label class="layui-form-label">座位:</label>
                            <div class="layui-input-inline">
                                <input
                                    type="text"
                                    id="screensSeat${keepIndex}"
                                    required
                                    lay-verify="required"
                                    placeholder="请输入座位" 
                                    autocomplete="off"
                                    class="layui-input div-width"
                                />
                            </div>
                            <div class="layui-input-block div-box">
                            <button type="button" class="layui-btn layui-btn-primary layui-border-inline div-look lookButton" lay-event="look" data-index="${keepIndex}">  
                            <i class="layui-icon">预览</i>
                            </button>
                           </div>   
                        </div>
                            `;
                            keepIndex++;
                            $('.box').append(str); //每点击一次增加一个子节点 多一个放映厅

                        });
                        //座位表
                        $(".box").on("click", ".lookButton", function () {
                            let keepIndex = $(this).attr('data-index'); //获取预览按钮的下标
                            if ($('[placeholder="请输入座位"]').val()) {
                                layer.open({ //弹出层打开
                                    type: 1,
                                    title: '座位表信息',
                                    area: ['400px', '300px'],
                                    offset: ['250px', '80px'],
                                    btn: ['关闭'],
                                    content: `
                                    <div id="seats"></div>
                                    `,
                                    success() {
                                        let screensSeat = JSON.parse($("#screensSeat" + keepIndex).val());
                                        // console.log(screensSeat); //得到二维数组 [[1,1,0,0],[0,0,1,1]]
                                        let str = screensSeat.map(item => `<div class="row">${item.map(item => {

                                            let seatTable = '';

                                            if (item == 1) {

                                                seatTable += `<span class="seatTable red"></span>`

                                            } else if (item == 0) {

                                                seatTable += `<span class="seatTable black"></span>`

                                            }

                                            return seatTable

                                        }).join('')}</div>`).join('');
                                        // console.log(str);得到有样式的拼接座位字符串
                                        $('#seats').html(str); //进行渲染
                                    }

                                });
                            }
                        });

                        form.render(); //渲染表单
                    },
                    content: `
                    <style>
                    .margin{
                        margin-top:15px;
                    }
                    .center{
                        display: flex;
                        justify-content: center;
                    }
                    .box{
                        margin: auto;
                        margin-top:15px;
                    }
                    .div-width{
                        width: 250px;
                    }
                    .flex{
                        display: flex;
                    }
                    .div-box{
                        margin-left: 60px;
                    }
                    .div-look{
                        border-color: rgb(45, 186, 191);
                        color: rgb(45, 186, 191);
                        padding-left:10px;
                        padding-right:10px;
                    }
                    .div-look:hover{
                        border-color: rgb(45, 186, 191);
                        color: rgb(45, 186, 191);
                       
                    }
                    
                </style>
                    <form class="layui-form" lay-filter="addForm">
                    <div class="layui-form-item margin">
                        <label class="layui-form-label">院线名:</label>
                        <div class="layui-input-inline">
                            <input
                                type="text"
                                name="name"
                                required
                                lay-verify="required"
                                placeholder="请输入院线名"
                                autocomplete="off"
                                class="layui-input width"
                            />
                        </div>
                    </div>
                    <div class="layui-form-item margin">
                    <label class="layui-form-label">地址:</label>
                    <div class="layui-input-inline">
                        <input
                            type="text"
                            name="address"
                            required
                            lay-verify="required"
                            placeholder="请输入地址"
                            autocomplete="off"
                            class="layui-input width"
                        />
                    </div>
                </div>
                <div class="layui-form-item margin">
                <label class="layui-form-label">官方电话:</label>
                <div class="layui-input-inline">
                    <input
                        type="text"
                        name="phone"
                        required
                        lay-verify="required"
                        placeholder="请输入官方电话"
                        autocomplete="off"
                        class="layui-input width"
                    />
                </div>
            </div>
            <div class="layui-form-item margin">
            <label class="layui-form-label">官方网站:</label>
            <div class="layui-input-inline">
                <input
                    type="text"
                    name="email"
                    required
                    lay-verify="required"
                    placeholder="请输入官方网站"
                    autocomplete="off"
                    class="layui-input width"
                />
            </div>
        </div>
        <div class="layui-input-inline center">
        <button type="button" class="layui-btn layui-btn-primary layui-border-black" id="addScreens">  
        <i class="layui-icon">&#xe654;</i>
        <i class="layui-icon">新增放映厅</i>
        </button>
        </div>
        <div class="box">
   
        </div>
                    </form>
                    `
                });

            }
            else if (obj.event == "search") {
                // console.log(form.val('searchForm'));
                table.reload('cinemaTable', { //自定义表格重载 
                    where: form.val('searchForm'),//设定异步数据接口的额外参数 form.val('searchForm')获取表单区域所有值  lay-filter="searchForm"
                    page: {
                        curr: 1 //重新从第 1 页开始
                    }
                });
            }
        });

        table.on('tool(cinemaTable)', function (obj) {
            // console.log(obj);
            if (obj.event == 'delete') {
                // 删除院线
                layer.confirm('是否删除？', function (index) {
                    $.ajax({
                        type: "delete",
                        url: '/cinema/' + obj.data._id,
                        success() {
                            table.reload('cinemaTable');
                            layer.close(index);
                        }
                    });

                });
            }
            else if (obj.event == 'edit') {
                let keepIndex = 0;
                layer.open({
                    type: 1,
                    title: '修改院线信息',
                    area: ['500px', '400px'],
                    btn: ['确定修改', '取消'],
                    yes: function (index) {
                        let screens = [];
                        for (let i = 0; i < keepIndex; i++) {
                            if ($("#cutSeats" + i).length > 0) {
                                screens.push({
                                    name: $("#cutScreensName" + i).val(),
                                    seat: JSON.parse($("#cutScreensSeat" + i).val())
                                });
                            }
                        }
                        $.ajax({ //确认修改
                            type: "put",
                            url: "/cinema/" + obj.data._id,
                            data: {
                                ...form.val('updateForm'), screens: JSON.stringify(screens)
                            },
                            success() {
                                table.reload("cinemaTable");
                                layer.close(index);
                            }
                        });

                    },
                    success: function () { //弹出层成功出现
                        $.ajax({ //信息回填
                            type: "get",
                            url: "/cinema/" + obj.data._id,
                            success(res) { //获取服务器返回的数据f 
                                //回填座位数据
                                keepIndex = res.screens.length;
                                let str = res.screens.map(function (item, index) {
                                    let screensSeat = JSON.stringify(item.seat);
                                    let seatTable = '';
                                    seatTable += `<div id="cutSeats${index}">
                                        <div class="layui-form-item">
                                        <label class="layui-form-label">放映厅:</label>
                                        <div class="layui-input-inline">
                                            <input
                                                type="text"
                                                id="cutScreensName${index}"
                                                required
                                                lay-verify="required"
                                                value=${item.name}
                                                autocomplete="off"
                                                class="layui-input div-width"
                                            />
                                        </div>
                                    </div>
                                    <div class="layui-form-item flex">
                                        <label class="layui-form-label">座位:</label>
                                        <div class="layui-input-inline">
                                            <input
                                                type="text"
                                                id="cutScreensSeat${index}"
                                                required
                                                lay-verify="required"
                                                value=${screensSeat}
                                                autocomplete="off"
                                                class="layui-input div-width"
                                            />
                                        </div>
                                       
                                        <button type="button" class="layui-btn layui-btn-primary layui-border-inline div-look lookButton" lay-event="look" data-index="${index}">  
                                        <i class="layui-icon">预览</i>
                                        </button>
                                        
                                    </div>`
                                    return seatTable

                                }).join('');
                                $('.box').append(str);
                                form.val('updateForm', res);
                            }
                        });
                        //座位表
                        $(".box").on("click", ".lookButton", function () {
                            let index = $(this).attr('data-index');
                            layer.open({ //弹出层打开
                                type: 1,
                                title: '座位表信息',
                                area: ['400px', '300px'],
                                offset: ['250px', '80px'],
                                btn: ['关闭'],
                                content: `
                                    <div id="seats"></div>
                                    `,
                                success() {
                                    let screensSeat = JSON.parse($("#cutScreensSeat" + index).val());
                                    // console.log(screensSeat); //得到二维数组 [[1,1,0,0],[0,0,1,1]]
                                    let str = screensSeat.map(item => `<div class="row">${item.map(item => {

                                        let seatTable = '';

                                        if (item == 1) {

                                            seatTable += `<span class="seatTable red"></span>`

                                        } else if (item == 0) {

                                            seatTable += `<span class="seatTable black"></span>`

                                        }

                                        return seatTable

                                    }).join('')}</div>`).join('');
                                    // console.log(str);得到有样式的拼接座位字符串
                                    $('#seats').html(str); //进行渲染
                                }

                            });

                        });
                        form.render();
                    },
                    content: `
                    <form class="layui-form" lay-filter="updateForm">
                    <div class="layui-form-item margin">
                    <label class="layui-form-label">院线名:</label>
                    <div class="layui-input-inline">
                        <input
                            type="text"
                            name="name"
                            required
                            lay-verify="required"
                            placeholder="请输入院线名"
                            autocomplete="off"
                            class="layui-input width"
                        />
                    </div>
                </div>
                <div class="layui-form-item margin">
                <label class="layui-form-label">地址:</label>
                <div class="layui-input-inline">
                    <input
                        type="text"
                        name="address"
                        required
                        lay-verify="required"
                        placeholder="请输入地址"
                        autocomplete="off"
                        class="layui-input width"
                    />
                </div>
            </div>
            <div class="layui-form-item margin">
            <label class="layui-form-label">官方电话:</label>
            <div class="layui-input-inline">
                <input
                    type="text"
                    name="phone"
                    required
                    lay-verify="required"
                    placeholder="请输入官方电话"
                    autocomplete="off"
                    class="layui-input width"
                />
            </div>
        </div>
        <div class="layui-form-item margin">
        <label class="layui-form-label">官方网站:</label>
        <div class="layui-input-inline">
            <input
                type="text"
                name="email"
                required
                lay-verify="required"
                placeholder="请输入官方网站"
                autocomplete="off"
                class="layui-input width"
            />
        </div>
    </div>
   
    <div class="box">

    </div>
                </form>
                    `
                });
            }
        });
    }
}